<?php

    include "../database.php";

    $user_id_addStory = $_POST["usr_id"];
    $queryProject = "SELECT current_project FROM user WHERE id = '$user_id_addStory'";
    $resProject = executeQuery($queryProject);
    $row = mysql_fetch_array($resProject);
    $curr_proj = $row["current_project"];
        
    $title=$_POST["title"];
    $content=nl2br($_POST["content"]);
    $tests=nl2br($_POST["tests"]);
    if (isset($_POST["prior"]))
        $priority=$_POST["prior"];
    else
        $priority=0;
    $value=$_POST["value"];
    $nmr = 0;
    
    if (is_numeric($value) && $value > 0 && $value < 11)
            $nmr = 1;
    
    if(!isset($title) || $title == ""){
        if($nmr > 0)
            $data = array('bool' => '1', 'success' => '0', 'ttl' => '0', 'aux' => '0');
        else
            $data = array('bool' => '1', 'success' => '0', 'ttl' => '0', 'aux' => '100');
    }
    else{
    
        if (!isset($content))
            $content = "";
        if (!isset($tests))
            $tests = "";
        if (!isset($priority) || $priority < 1)
            $priority = "";

        $content = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "", $content);
        $tests = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "", $content);;

        $queryTest = "SELECT * FROM story WHERE story_title = '$title' and project_id = '$curr_proj'";
        $res = executeQuery($queryTest);
        $numRows = mysql_num_rows($res);
        $ttl_missing = 1;
        $ttl = 0;   

        //Zgodbo spremenimo samo, če zgodba s takim imenom še ne obstaja v bazi

            //$ttl_missing = 0;
        if($numRows == 0 )
            $ttl = 1;
        //In ce je bussiness value ustrezen

        if ($ttl > 0 && $nmr > 0 && $ttl_missing > 0){
            $query = "INSERT INTO `TPO15_2013`.`story` (`project_id`, `story_title`, `story_text`, `story_test`, `story_priority`, `story_value`) VALUES ('$curr_proj', '$title', '$content', '$tests', '$priority', '$value')";
            $result = executeQuery($query);
            $data = array('bool' => '0', 'success' => '1', 'ttl' => '1', 'aux' => '0');
        }
        else if ($ttl > 0 && $nmr < 1)
            $data = array('bool' => '1', 'success' => '0', 'ttl' => '1', 'aux' => '100');
        else if ($ttl < 1 && $nmr > 0)
            $data = array('bool' => '2', 'success' => '0', 'ttl' => '1', 'aux' => '0');
        else
            $data = array('bool' => '3', 'success' => '0', 'ttl' => '1', 'aux' => 'undef');
    }
    echo json_encode($data);

?>
